package hichecker.ui.custom_views.series;

import hichecker.controller.Config;
import hichecker.controller.MainController;
import hichecker.ui.components.custom_table.CustomTable;
import hichecker.ui.general_views.container_panel.content.ContentPanel;
import hichecker.university.Series;
import hichecker.university.UniversityPart;

import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.GroupLayout;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class SeriesSettings extends ContentPanel {
	private final MainController controller;

	private CustomTable tblSeries;
	private SeriesSettingsTableModel model;
	private Series series;

	public SeriesSettings(UniversityPart item, MainController controller) {
		super(item);
		this.controller = controller;
		this.series = (Series) item;

		JLabel lblName = new JLabel(Config.SERIES_NAME);
		JTextField txtName = new JTextField(series.getName());
		txtName.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				super.keyPressed(e);
				changeSeriesName((JTextField) e.getSource());
			}
		});

		model = new SeriesSettingsTableModel(series);
		tblSeries = new CustomTable(model, getWidth());
		JScrollPane pane = new JScrollPane(tblSeries);

		GroupLayout layout = new GroupLayout(this);

		layout.setAutoCreateGaps(true);
		layout.setAutoCreateContainerGaps(true);

		layout.setHorizontalGroup(layout.createParallelGroup()
			.addGroup(layout.createSequentialGroup()
				.addComponent(lblName)
				.addComponent(txtName)
			)
			.addComponent(pane)
		);

		layout.setVerticalGroup(layout.createSequentialGroup()
			.addGroup(layout.createParallelGroup()
				.addComponent(lblName)
				.addComponent(txtName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
			)
			.addComponent(pane)
		);

		setLayout(layout);
	}

	@Override
	public void paint(Graphics g) {
		tblSeries.setAutoResizeable(getWidth());
		super.paint(g);
	}

	@Override
	public ContentPanel switchViewSettings() {
		return new SeriesView(item, controller);
	}

	public void changeSeriesName(JTextField field) {
		series.setName(field.getText());
		controller.fireItemUpdate();
	}
}
